<template>
  <TopBar></TopBar>
  <div class="chat-app">
    <div class="chat-container">
      <!-- 左侧边栏 -->
      <div class="sidebar">
        <h2>选择AI模型</h2>
        <ul class="model-list">
          <li v-for="model in aiModels" :key="model" :class="['model-item', { active: model === currentModel }]"
            @click="selectModel(model)">
            <el-icon :size="30">
              <el-image :src="modelIcons[model]"></el-image>
            </el-icon>
            &nbsp;&nbsp;&nbsp;{{ model }}
          </li>
        </ul>
      </div>

      <!-- 主聊天区域 -->
      <div class="main-chat">
        <div class="chat-messages" ref="chatMessagesRef">
          <div v-for="(message, index) in messages" :key="index"
            :class="['message', message.isUser ? 'user-message' : 'ai-message']">
            <div class="message-content">
              <div class="message-avatar">
                <!-- {{ message.isUser ? '👤' : modelIcons[currentModel] }} -->
                <el-icon v-if="message.isUser" :size="45">
                  <el-image style="border-radius: 50%;" :src="user.avatar"></el-image>
                </el-icon>
                <el-icon v-else :size="30">
                  <el-image :src="modelIcons[currentModel]"></el-image>
                </el-icon>
              </div>
              <div class="message-text">
                <template v-if="message.isStreaming">
                  {{ message.content }}<span class="cursor"></span>
                </template>
                <template v-else>
                  {{ message.content }}
                </template>
                <div class="message-meta">
                  <span class="message-time">{{ message.time }}</span>
                  <button class="copy-btn" @click="copyMessage(message.content)">复制</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="input-area">
          <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="输入消息..."
            :disabled="isProcessing" />
          <button @click="sendMessage" :disabled="isProcessing">
            <span v-if="!isProcessing">发送</span>
            <span v-else class="sending-indicator"></span>
          </button>
        </div>
      </div>
    </div>
  </div>
  <Footer></Footer>
</template>

<script setup>
import TopBar from '@/component/TopBar.vue';
import Footer from '@/component/Footer.vue';
import { ref, reactive, watch, nextTick } from 'vue';
import { onMounted } from 'vue'
import request from '../../utils/request';

const user = ref({});

const getUserInfo = () => {
    const uid = sessionStorage.getItem('uid');
    if (uid) {
        const uidObj = JSON.parse(uid);
        request.get('/api/user/GetUserInfo', {
            params: {
                uid: uidObj
            }
        }).then(res => {
            user.value = res.data;
        }).catch(error => {
            console.error("请求失败", error);
        })
    } else {
        console.log("未登录");
        user.value.avatar = "https://bu.dusays.com/2024/12/28/677018da4485e.png";
    }
}

// 初始化加载
onMounted(async () => {
    await getUserInfo();
    console.log(user.value);
})


// AI 模型列表和图标
const aiModels = [ 'DeepSeek','智谱AI', 'Coze'];
const modelIcons = {
  'DeepSeek': 'https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/icons/Deepseek.png',
  '智谱AI': 'https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/icons/zhipuqingyan.png',
  'Coze': 'https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/icons/coze.png'
};

// 响应式数据
const currentModel = ref('DeepSeek');
const messages = reactive([]);
const userInput = ref('');
const chatMessagesRef = ref(null);
const isProcessing = ref(false);

// 切换 AI 模型
function selectModel(model) {
  if (confirm(`切换到 ${model} 将清空聊天记录，确定吗？`)) {
    currentModel.value = model;
    messages.length = 0;
  }
}

//deepseek
const ChatDeepSeek=(content)=>{
  request.post("/api/ollama/deepseek",{message:content})
  .then(res=>{

  })
}

// 发送消息
async function sendMessage(async) {
  if (userInput.value.trim() === '' || isProcessing.value) return;

  isProcessing.value = true;

  const messageReply=ref(null)
  await request.post("/api/ollama/deepseek",{message:userInput.value})
  .then(res=>{
    console.log(res);
    messageReply.value=res.message
  })

  const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  messages.push({ content:userInput.value, isUser: true, time, isStreaming: false });
  userInput.value = '';

  await nextTick();
  scrollToBottom();

  const aiMessage = reactive({ content: '', isUser: false, isStreaming: true, time });
  messages.push(aiMessage);

  const response = `${ messageReply.value}`;
  const typingSpeed = 50;

  for (let i = 0; i < response.length; i++) {
    await new Promise(resolve => setTimeout(resolve, typingSpeed));
    aiMessage.content = response.slice(0, i + 1);
    await nextTick();
    scrollToBottom();
  }

  aiMessage.isStreaming = false;
  isProcessing.value = false;
  await nextTick();
  scrollToBottom();
}

// 滚动到底部
function scrollToBottom() {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
}

// 复制消息内容
function copyMessage(content) {
  navigator.clipboard.writeText(content).then(() => {
    alert('已复制到剪贴板！');
  });
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick().then(scrollToBottom);
}, { deep: true });
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap');

.chat-app {
  display: flex;
  flex-direction: column;
  height: 80vh;
  font-family: 'Roboto', sans-serif;
  background: linear-gradient(135deg, #e0e7ff 0%, #f9faff 100%);
}

.chat-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  background: #ffffff;
  padding: 25px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  border-radius: 0 20px 20px 0;
  overflow-y: auto;
}

.sidebar h2 {
  font-size: 20px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 25px;
  letter-spacing: 0.5px;
}

.model-list {
  list-style-type: none;
  padding: 0;
}

.model-item {
  display: flex;
  align-items: center;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  margin-bottom: 10px;
  background: #f8fafc;
}

.model-item:hover {
  background: #eef2ff;
  transform: translateX(5px);
}

.model-item.active {
  background: linear-gradient(90deg, #4f46e5, #7c3aed);
  color: white;
  box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
}

.model-icon {
  margin-right: 12px;
  font-size: 24px;
}

/* 主聊天区域样式 */
.main-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 20px 0 0 20px;
  margin: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 25px;
  background: #fafafa;
  border-radius: 20px 20px 0 0;
}

.message {
  max-width: 70%;
  margin-bottom: 20px;
  clear: both;
  transition: all 0.3s ease;
}

.message-content {
  display: flex;
  align-items: flex-start;
}

.message-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 15px;
  background: linear-gradient(135deg, #d1d5db, #e5e7eb);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-message .message-avatar {
  margin-right: 0;
  margin-left: 15px;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  color: white;
}

.message-text {
  padding: 15px 20px;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  line-height: 1.5;
  font-size: 16px;
  position: relative;
  animation: slideIn 0.4s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-message {
  float: right;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.user-message .message-text {
  background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
  color: #2c3e50;
}

.ai-message .message-text {
  background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
  color: #2c3e50;
}

/* 输入区域样式 */
.input-area {
  display: flex;
  padding: 20px;
  background: #ffffff;
  border-top: 1px solid #e5e7eb;
  border-radius: 0 0 20px 20px;
}

.input-area input {
  flex: 1;
  padding: 14px 20px;
  border: none;
  border-radius: 30px;
  margin-right: 15px;
  font-size: 16px;
  background: #f1f3f5;
  transition: all 0.3s ease;
  box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.05);
}

.input-area input:focus {
  outline: none;
  background: #ffffff;
  box-shadow: 0 0 10px rgba(79, 70, 229, 0.2);
}

.input-area button {
  padding: 14px 30px;
  background: linear-gradient(90deg, #4f46e5, #7c3aed);
  color: white;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
}

.input-area button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(79, 70, 229, 0.4);
}

.input-area button:disabled {
  background: #d1d5db;
  box-shadow: none;
  cursor: not-allowed;
}

/* 流式光标和发送动画 */
.cursor {
  display: inline-block;
  width: 12px;
  height: 22px;
  background: #4f46e5;
  margin-left: 5px;
  animation: blink 0.8s infinite;
}

@keyframes blink {
  0% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

.sending-indicator {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid #ffffff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 消息元信息样式 */
.message-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
  display: flex;
  justify-content: space-between;
  opacity: 0.8;
}

.message-time {
  font-weight: 400;
}

.copy-btn {
  background: none;
  border: none;
  color: #4f46e5;
  cursor: pointer;
  padding: 0;
  font-size: 12px;
  transition: color 0.3s ease;
}

.copy-btn:hover {
  color: #7c3aed;
  text-decoration: underline;
}
</style>